"""
获取到可用的节点（即在主路上的节点）
"""
import os
import json
from PIL import Image
import concurrent.futures
from parse_config import Config

def get_nodes_position(plain_nodes_path):
    with open(plain_nodes_path,'r') as f:
        plain_nodes=json.load(f)
    return plain_nodes

def count_non_white_segments(image_path, y):
    image = Image.open(image_path)
    width, height = image.size

    # 检查y坐标是否在图像范围内
    if y < 0 or y >= height:
        return 0

    is_white = True
    segment_count = 0

    for x in range(width-10):
        pixel = image.getpixel((x, y))
        # 对于RGB图像，白色是(255, 255, 255)；对于RGBA图像，白色是(255, 255, 255, 255)
        if len(pixel) == 3:
            is_current_white = pixel == (255, 255, 255)
        elif len(pixel) == 4:
            is_current_white = pixel == (255, 255, 255, 255)
        else:
            raise ValueError("不支持的图像模式")

        if not is_current_white and is_white:
            segment_count += 1
            is_white = False
        elif is_current_white:
            is_white = True

    return segment_count

def process_node(name, node, image_path):
    try:
        count = count_non_white_segments(image_path, int(node[1]))
        if count == 1:
            return name
    except ValueError as e:
        print(e)
    return None


def get_valid_split_nodes(plain_nodes, image_path):
    valid_split_nodes = set()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        # 提交任务到进程池
        future_to_name = {executor.submit(process_node, name, node, image_path): name for name, node in
                          plain_nodes.items()}
        for future in concurrent.futures.as_completed(future_to_name):
            result = future.result()
            if result is not None:
                valid_split_nodes.add(result)
    return valid_split_nodes

def main():
    config_path='./config.json'
    config=Config(config_path)
    plain_nodes=get_nodes_position(config.config['plain_result_save_path'])
    valid_nodes=list(get_valid_split_nodes(plain_nodes,config.config['formal_computation_pic_save_path']))
    with open(config.config['valid_nodes_save_path'],'w') as f:
        json.dump(valid_nodes,f)
    
    
if __name__=='__main__':
    main()
    
    